<template>
	<div class="login">
		<el-card class="columnnav">
			<template #header>
				<div class="button-container">
					<h4>后台登陆</h4>
				</div>
			</template>
			<el-form :model="form" ref="form" label-width="90px" :rules="rules">
				<el-form-item label="管理账号:" aria-placeholder="请设置管理员账号" prop="username">
					<el-input v-model="form.username" />
				</el-form-item>
				<el-form-item label="管理密码:" prop="password">
					<el-input v-model="form.password" aria-placeholder="请设置管理员密码" show-password />
				</el-form-item>
			</el-form>
			<div class="button-container">
				<el-button type="primary" @click="register" :loading="loading">登陆后台</el-button>
			</div>
		</el-card>
	</div>
</template>
<script>
	import { dataRequest as api, automaticLogin } from '@/api/api'
	import sha256 from 'crypto-js/sha256'
	export default {
		data() {
			return {
				loading: false,
				form: {
					domain: window.location.hostname.toLowerCase().replace(/^www\./, ''),
					username: '',
					password: '',
				},
				rules: {
					username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
					password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
				},
			}
		},
		methods: {
			async register() {
				this.loading = true
				this.$refs['form'].validate(async (valid) => {
					if (valid) {
						let data = { ...this.form }
						data.password = sha256(sha256(data.password)).toString()
						// 注册的代码
						let arr = await api('Create', 'JWT', data)

						if (arr.code == 200) {
							const data = { id: 1, JWT: arr.data, userid: arr.massage, logon: false }
							if (await this.$indexedDB.getObject(data.id)) {
								// 存在修改
								this.$indexedDB.updateObject(data)
							} else {
								// 不存在 添加
								this.$indexedDB.addObject(data)
							}
							let array = await automaticLogin()
							if (array.code == 200) {
								this.$router.push('/admin')
								this.$message.success('登陆成功')
								// 跳转到 /about 路径
							}
						} else {
							this.$message.error('账号不存在或密码错误')
						}
					} else {
						this.loading = false
						return false
					}
					this.loading = false
				})
			},
		},
	}
</script>
<style scoped>
	.login {
		height: 100%;
		background: #303133;
		display: flex;
		justify-content: center; /* 水平居中 */
		align-items: center; /* 垂直居中 */
	}
	.columnnav {
		margin: auto;

		width: 400px !important;
	}
	.button-container {
		display: flex;
		justify-content: center; /* 水平居中 */
	}
</style>
